<template>
  <div class="user-profile">
    <heads title="个人资料"></heads>
    <div class="main-content">
 
      <van-form @submit="Submit">
         <van-field name="uploader" label="头像">
          <template #input>
           <div class="img-list" v-for="(item,index) in fileList" :key="index" :style="{backgroundImage:'url('+item.url+')'}"></div>
            
          <van-uploader  :max-count="1"  :deletable="false"   preview-size="1.4rem" :after-read="uploadForehead" >
             
          </van-uploader>
          </template>
        </van-field>

        <van-field
          v-model="userInfo.userId"
          name="会员ID"
          label="会员ID"
          placeholder="请输入会员ID"
          :readonly="true"
        />
        <van-field
          v-model="username"
          center
          clearable
          label="昵称"
          placeholder="请输入昵称"
        >
        </van-field>
        <van-field name="radio" label="性别">
          <template #input>
            <van-radio-group v-model="sex" direction="horizontal">
              <van-radio name="1">男</van-radio>
              <van-radio name="2">女</van-radio>
            </van-radio-group>
          </template>
        </van-field>
        <!-- 输入手机号，调起手机号键盘 -->
        <van-field v-model="tel" type="tel" label="手机号"  :readonly="true" placeholder="请输入手机号"/>
             <!-- <van-field
          readonly
          clickable
          name="area"
          :value="region"
          label="国家"
          placeholder="点击选择国家"
          @click="showArea = true"
          is-link
        />
        <van-field
          readonly
          clickable
          name="area"
          :value="region"
          label="地址"
          placeholder="点击选择省市区"
          @click="showArea = true"
          is-link
        /> -->
        <!-- <van-field
            readonly
            clickable
            name="country"
            :value="country"
            label="国家"
            placeholder="请选择"
            @click="showCountry = true"
            is-link
          /> -->
          <van-field
            readonly
            clickable
            name="area"
            :value="region"
            :disabled="areaList[0].values.length > 0 ? false : true"
            label="地址"
            placeholder="点击选择省市区"
            @click="areaList[0].values.length > 0 ? (showArea = true) : ''"
            is-link
          />

        <!-- <van-popup v-model="showArea" position="bottom">
          <van-area
            :area-list="areaList"
            @confirm="onConfirm"
            @cancel="showArea = false"
          />
        </van-popup> -->
         <!-- 国家弹框 -->
      <van-popup v-model="showCountry" round position="bottom">
        <van-picker
          show-toolbar
          :columns="countryList"
          ref="countryPicker"
          title="国家"
          :loading="countryLoading"
          @confirm="countryChange"
          @cancel="showCountry = false"
        />
      </van-popup>
      <!-- end -->
             <!-- 省市区弹框 -->
      <van-popup v-model="showArea" round position="bottom">
        <van-picker
          show-toolbar
          :columns="areaList"
          ref="areaPicker"
          title="地区"
          :loading="areaLoading"
          @confirm="regionChange"
          @cancel="showArea = false"
          @change="areaSelect"
        />
      </van-popup>
      <!-- end -->
        <div class="btn-box">
          <van-button type="info" round class="btn-common" native-type="submit" loading-text="修改中..." :loading="loading">
            保存
          </van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script>
import adressList from "@/js/json/area.js";
import { mapState } from "vuex";
export default {
  components: {
    heads: resolve => require(["@/components/common/heads"], resolve)
  },
  data() {
    return {
      username: "",// 昵称
      country: "", // 国家
        region: "", // 地区
      sex:'',// 性别
      tel:'',// 手机
      uploader:'',// 头像
      showArea: false,
       showCountry: false, // 国家弹框
      fileList:[],
      fileIds:[],// 图片集合
      loading:false,
     countryValue: "", // 国家id
      countryIndex: "", // 国家选中索引
      provinceValue: "", // 省份id
      provinceIndex: "", // 省份选中索引
      cityValue: "", // 城市id
      cityIndex: "", // 城市选中索引
      areaValue: "", // 城市id
      areaIndex: "", // 城市选中索引
      areaLoading: false,
      countryLoading: false,
      // areaList: adressList // 数据格式见 Area 组件文档
       areaList: [
        // 地区
        // 第一列
        {
          values: [],
          ids: [],
          defaultIndex: 0
        },
        // 第二列
        {
          values: [],
          ids: [],
          defaultIndex: 0
        },
        // 第三列
        {
          values: [],
          ids: [],
          defaultIndex: 0
        }
      ],
        countryList: [
        // 国家
        // 第一列
        {
          values: [],
          ids: [],
          defaultIndex: 0
        }
      ],
    };
  },
  computed: {
    ...mapState(["userInfo"])
  },
  watch: {
     // 国家改变时
    countryValue: {
      handler(newVal, oldVal) {
        this.getProvinceData({ parentAreaId: newVal });
      }
    },
    // 国家索引改变时
    countryIndex: {
      handler(newVal, oldVal) {
        this.countryValue = this.countryList[0].ids[newVal];
      }
    },
    // 省份改变时
    provinceValue: {
      handler(newVal, oldVal) {
        this.getCityData({ parentAreaId: newVal });
      },
      immediate:true,
      deep: true
    },
    // 省份索引改变时
    // provinceIndex:{
    //   handler(newVal,oldVal){
    //     this.areaList[1] = this.$options.data().areaList[1]
    //      this.areaList[2] = this.$options.data().areaList[2]
    //     this.provinceValue = this.areaList[0].ids[newVal]

    //   },
    // },
    // 城市改变时
    cityValue: {
      handler(newVal, oldVal) {
        this.getAreaData({ parentAreaId: newVal });
      },
      deep: true
    }
  },
  methods: {
    // 地区选中时
    areaSelect(e) {
      let _this = this;

      _this.provinceIndex = _this.$refs.areaPicker.getIndexes()[0];
      _this.cityIndex = _this.$refs.areaPicker.getIndexes()[1];
      _this.areaIndex = _this.$refs.areaPicker.getIndexes()[2];

      _this.provinceValue =
        _this.areaList[0].ids[_this.$refs.areaPicker.getIndexes()[0]];
      _this.cityValue =
        _this.areaList[1].ids[_this.$refs.areaPicker.getIndexes()[1]];
      _this.areaValue =
        _this.areaList[2].ids[_this.$refs.areaPicker.getIndexes()[2]];
    },
    // 地区选择
    regionChange(e) {
      let _this = this;

      _this.region = `${e[0]}-${e[1]}-${e[2]}`;
      _this.showArea = false;
      console.log(e);
    },
     // 国家改变
    countryChange(e) {
      let _this = this;
      _this.country = `${e[0]}`;
      _this.countryIndex = _this.countryList[0].values.indexOf(e[0]);
      _this.showCountry = false;
    },
    // 地区选择
    // onConfirm(values) {
    //   this.region = values.map(item => item.name).join("/");
    //    this.regionCode = values.map(item => item.code);
    
    //   this.showArea = false;
    // },
        // 获取国家数据
    getCountryData() {
      let _this = this;
      _this.countryLoading = true;
      this.$ajax
        .post(`${this.$baseUrl}/portal/areas/getCountryList`, {})
        .then(function(res) {
          if (res.data.code == 200) {
            _this.countryLoading = false;
            // 一级
            res.data.data.map((item, index) => {
              _this.countryList[0].values.push(item.name);
              _this.countryList[0].ids.push(item.areaId);
            });
            _this.countryValue =
              res.data.data[_this.areaList[0].defaultIndex].areaId;
          }
        })
        .catch(function(error) {
          _this.areaLoading = false;

          console.log(error);
        });
    },
    // 获取省份数据
    getProvinceData(_param) {
      let _this = this;
      _this.areaLoading = true;
      this.$ajax
        .post(`${this.$baseUrl}/portal/areas/getChildAreaList`, _param)
        .then(function(res) {
          if (res.data.code == 200) {
            _this.areaLoading = false;
            _this.areaList[0].values = [];
            _this.areaList[0].ids = [];
            // 一级
            res.data.data.map((item, index) => {
              _this.areaList[0].values.push(item.name);
              _this.areaList[0].ids.push(item.areaId);
            });
           
                _this.areaList[0].defaultIndex = _this.areaList[0].values.indexOf(_this.userInfo.addressDetail.substring(0,_this.userInfo.addressDetail.indexOf('-')))
                 _this.provinceValue =
              res.data.data[_this.areaList[0].defaultIndex].areaId;
          }
        })
        .catch(function(error) {
          _this.areaLoading = false;

          console.log(error);
        });
    },
      // 获取城市数据
    getCityData(_param) {
      let _this = this;
      _this.areaLoading = true;

      this.$ajax
        .post(`${this.$baseUrl}/portal/areas/getChildAreaList`, _param)
        .then(function(res) {
          if (res.data.code == 200) {
            _this.areaLoading = false;
            _this.areaList[1].values = [];
            _this.areaList[1].ids = [];
            // 一级
            res.data.data.map((item, index) => {
              _this.areaList[1].values.push(item.name);
              _this.areaList[1].ids.push(item.areaId);
            });
            _this.cityValue = res.data.data[0].areaId;
            _this.areaList[1].defaultIndex = _this.areaList[1].values.indexOf(_this.userInfo.addressDetail.substring(_this.userInfo.addressDetail.indexOf('-')+1,_this.userInfo.addressDetail.lastIndexOf('-')))
            _this.$forceUpdate();
          }
        })
        .catch(function(error) {
          _this.areaLoading = false;

          console.log(error);
        });
    },
    // 获取县城数据
    getAreaData(_param) {
      let _this = this;
      _this.areaLoading = true;

      this.$ajax
        .post(`${this.$baseUrl}/portal/areas/getChildAreaList`, _param)
        .then(function(res) {
          if (res.data.code == 200) {
            _this.areaLoading = false;
            _this.areaList[2].values = [];
            _this.areaList[2].ids = [];
            // 一级
            res.data.data.map((item, index) => {
              _this.areaList[2].values.push(item.name);
              _this.areaList[2].ids.push(item.areaId);
            });

            _this.areaValue = res.data.data[0].areaId;
            _this.areaList[2].defaultIndex = _this.areaList[2].values.indexOf(_this.userInfo.addressDetail.substring(_this.userInfo.addressDetail.lastIndexOf('-')+1,_this.userInfo.addressDetail.length))
            _this.$forceUpdate();
          }
        })
        .catch(function(error) {
          _this.areaLoading = false;

          console.log(error);
        });
    },
    // 头像上传
    uploadForehead(file) {
    let _this = this;
    
      let formData = new FormData();
        formData.append('file', file.file);
        // file.status = 'uploading';
        // file.message = '上传中...';
            this.$ajax
        .post(`${this.$baseUrl}/portal/picture/avatar/upload?userId=${ _this.userInfo.userId }`, formData)
        .then(function(res) {
           file.status = '';
        file.message = '';
          if (res.data.code == 200) {
            _this.fileList = [
              {
                url:res.data.data[0].pictureUrl
              }
            ]
            console.log('上传的图片', _this.fileList)
            _this.fileIds = _this.fileIds.concat(res.data.data[0])
                    
          }
        })
        .catch(function(error) {
            file.status = '';
        file.message = '';
          console.log(error);
        });
      
    },

    Submit(values) {
      let _this = this;
      _this.loading = true;
      console.log('提交', _this.fileIds)
      let params = {
         "addressDetail": _this.region,
         "nick":_this.username,
        "avatar": _this.fileList[0].url ? _this.fileList[0].url : _this.userInfo.avatar,
        "cityId": _this.cityValue,
        "countyId":_this.areaValue,
        "mobile": _this.tel,
        "password": "",
        "provinceId": _this.provinceValue,
        "sex": _this.sex,
        "userId": _this.userInfo.userId
      };
      _this.$ajax
        .post(`${_this.$baseUrl}/portal/users/updateUser`, params)
        .then(function(res) {
          _this.loading = false;
          if (res.data.code == 200) {
             _this.$store.commit('saveUser',res.data.data[0]); 
             _this.$toast.success("修改成功!");
           
           
            
            setTimeout(() => {
               _this.$router.go(-1)
            }, 2000);
          }
        })
        .catch(function(error) {
                    _this.loading = false;

          console.log(error);
        });
    }
  },
  created() {
    let _this = this;
    this.getCountryData(); // 获取国家
    if(_this.userInfo.avatar){
      _this.fileList = [
        {
          url:_this.userInfo.avatar
        }
      ]
    }
    
    _this.username = _this.userInfo.nick
     _this.sex = _this.userInfo.sex+''
     _this.tel = _this.userInfo.mobile
     _this.region = _this.userInfo.addressDetail
   
     _this.$forceUpdate()
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss" scoped>
.user-profile {
  .main-content {
    min-height: 92vh;
  }
  .logo {
    width: 2.52rem;
    margin: 1rem auto;
  }
  .van-cell {
    padding: 0.3rem;
  }
  .btn-box {
    box-sizing: border-box;
    padding: 1.5rem 0.6rem;
  }
  /deep/ .van-uploader__preview{
    // margin-bottom: 0
    .van-uploader__preview-image{
      &:nth-child(2){
        display: none!important;
      }
    }
  }
  /deep/ .van-uploader__upload{
    width: 1.4rem;
    height: 1.4rem;
    border-radius: .2rem;
    margin: 0;
        display: -webkit-box!important;
    display: -webkit-flex!important;
    display: flex!important;
    opacity: 1!important;
    // position: absolute;
    // left: 0;
    // bottom: 0;
    // background: rgba($color: #000000, $alpha: .3)
  }
  .img-list{
     width: 1.4rem;
    height: 1.4rem;
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
    border-radius: .2rem;
    margin: 0;
    margin-right: .2rem;
  }
}
</style>
